import os
import subprocess


def convert_mhtml_to_pdf(mhtml_path, pdf_path):
    """
    将MHTML文件转换为PDF
    :param mhtml_path: 输入的MHTML文件路径
    :param pdf_path: 输出的PDF文件路径
    """
    # 转换为标准文件URL格式
    mhtml_url = f'file://{os.path.abspath(mhtml_path).replace(os.sep, "/")}'

    # 自动查找Edge安装路径（Windows系统）
    try:
        from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, KEY_READ
        with OpenKey(HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\msedge.exe", 0,
                     KEY_READ) as key:
            edge_path = QueryValue(key, None)
    except Exception:
        edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"

    # 构造命令行参数
    cmd = [
        edge_path,
        "--headless",  # 无头模式
        "--disable-gpu",  # 禁用GPU加速
        f"--print-to-pdf={os.path.abspath(pdf_path)}",
        mhtml_url
    ]

    # 执行转换命令
    process = subprocess.run(cmd, capture_output=True, text=True)

    if process.returncode == 0:
        print(f"成功生成PDF文件：{os.path.abspath(pdf_path)}")
        return True
    else:
        print("转换失败，错误信息：")
        print(process.stderr)
        return False


# 使用示例
if __name__ == '__main__':
    """
    读取D:\\mhtml文件夹下的所有MHTML文件，并转换为PDF文件，保存到D:\\pdf文件夹下
    """
    mhtml_path = r"D:\mhtml"
    pdf_path = r"D:\pdf"
    for file in os.listdir(mhtml_path):
        if file.endswith(".mhtml"):
            mhtml_file = os.path.join(mhtml_path, file)
            pdf_file = os.path.join(pdf_path, file.replace(".mhtml", ".pdf"))
            convert_mhtml_to_pdf(mhtml_file, pdf_file)
            print(f"正在转换完成：{mhtml_file}")
